package com.bioskinserver.kyoucr.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bioskinserver.kyoucr.common.lang.Result;
import com.bioskinserver.kyoucr.entity.UImag;
import com.bioskinserver.kyoucr.service.UImagService;
import com.bioskinserver.kyoucr.util.ReadApplicationUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 关注公众号：MarkerHub
 * @since 2021-06-03
 */
@Api(tags = "广告图片管理模块")
@Slf4j
@RestController
public class UImagController {

    @Autowired
    UImagService uImageService;

    @Autowired
    ReadApplicationUtil readApplicationUtil;

    @ApiOperation("分页展示广告图片接口")
    @GetMapping("/images")
    public Result list(@RequestParam(defaultValue = "1") @ApiParam("初始页数默认1") Integer currentPage) {
        Page page = new Page(currentPage, 5);
        IPage pageData = uImageService.page(page, new QueryWrapper<UImag>().orderByDesc("id"));
        return Result.succ(pageData);
    }

    @ApiOperation("删除广告图片接口")
    @GetMapping("/image/delete")
    public Result delete(@RequestParam Integer id) {
        Boolean uImag =uImageService.removeById (id);
        if(uImag) {
            return Result.succ(uImag);
        }else {
            return Result.fail("删除失败");
        }
    }

    @ApiOperation("更新广告图片接口")
    @GetMapping("/image/setguanggao")
    public Result setguanggao(@RequestParam @ApiParam("广告id") Integer id) {
        UImag uImag =uImageService.getById (id);
        uImag.setIsshow("1");
        boolean isSucc = uImageService.saveOrUpdate(uImag);
        LambdaQueryWrapper<UImag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(UImag::getId,id);
        List<UImag> uImags = uImageService.list(queryWrapper);
        for (UImag uImag1:uImags){
            uImag1.setIsshow("0");
        }
        uImageService.saveOrUpdateBatch(uImags);
        if(isSucc) {
            return Result.succ(uImag);
        }else {
            return Result.fail("更新失败");
        }
    }

    @ApiOperation("获取全部广告图片接口")
    @GetMapping("/image/getguanggao")
    public Result getguanggao() {
        LambdaQueryWrapper<UImag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UImag::getIsshow,"1");
        List<UImag> uImags = uImageService.list(queryWrapper);
        return Result.succ(uImags);
    }

    @ApiOperation("广告图片上传接口")
    @PostMapping("/imageUploud")
    public Result uploadPic(@RequestParam(value = "file", required = false) MultipartFile file ) throws IOException {
        //目前这里是写死的本地硬盘路径
        String path = readApplicationUtil.getFilePath();
        log.info("path:" + path);
        //获取文件名称
        String fileName = file.getOriginalFilename();
        //获取文件名后缀
        Calendar currTime = Calendar.getInstance();
        String time = String.valueOf(currTime.get(Calendar.YEAR))+String.valueOf((currTime.get(Calendar.MONTH)+1));
        //获取文件名后缀
        String suffix = fileName.substring(file.getOriginalFilename().lastIndexOf("."));
        suffix = suffix.toLowerCase();
        if(suffix.equals(".jpg") || suffix.equals(".jpeg") || suffix.equals(".png")/* || suffix.equals(".gif")*/){
            fileName = UUID.randomUUID().toString()+suffix;
            File targetFile = new File(path, fileName);
            if(!targetFile.getParentFile().exists()){    //注意，判断父级路径是否存在
                targetFile.getParentFile().mkdirs();
            }
            long size = 0;
            //保存
            try {
                file.transferTo(targetFile);
                size = file.getSize();
            } catch (Exception e) {
                e.printStackTrace();
                return Result.fail("上传失败！");
            }
            //项目url，这里可以使用常量或者去数据字典获取相应的url前缀；
            String fileUrl=readApplicationUtil.getFilePrefix()+fileName;
            //文件获取路径
            log.info("fileUrl:" + fileUrl);
            UImag uImag = new UImag();
            uImag.setImgurl(fileUrl);
            uImageService.saveOrUpdate(uImag);
            return Result.succ(uImag);
        }else{
            return Result.fail("图片格式有误，请上传.jpg、.png、.jpeg格式的文件");
        }

    }
}
